package cn.boyu.controller;


import cn.boyu.entity.SysUser;

import cn.boyu.query.SysUserQuery;
import cn.boyu.result.AjaxResult;
import cn.boyu.service.ISysUserService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;


/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author yn
 * @since 2022-11-22
 */
@RestController
@CrossOrigin
@RequestMapping("/sysUser")
public class SysUserController {

    @Autowired
    private ISysUserService sysUserService;

    @PostMapping("/login")
    public AjaxResult login(String username, String password) {
        System.out.println("username:" + username);
        System.out.println("password:" + password);
        SysUser userinfo = sysUserService.login(username, password);
        //生成token
        String token = sysUserService.setToken(userinfo);

        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        map.put("userinfo", userinfo);

        return AjaxResult.success("登录成功！", map);
    }


    //修改用户密码 (用户id，原密码，新密码，确认密码）
    @PostMapping("/editPassword")
    public AjaxResult editPassword(Long id, String password, String newPass, String rePass) {
        AjaxResult result = sysUserService.editPassword(id, password, newPass, rePass);
        return result;
    }

    //用户注册
    @PostMapping("/register")
    public AjaxResult register(String name,String nick,String phone,String password,String rePass) {
        sysUserService.register(name,nick,phone,password,rePass);
        return AjaxResult.success("注册成功！");

    }

    //显示列表  /  高级查询
    @GetMapping("/query")
    public AjaxResult query(SysUserQuery qo) {
        IPage<SysUser> page = sysUserService.queryPage(qo);
        return AjaxResult.success(page);
    }
    //新增
    @PostMapping("save")
    public AjaxResult save(SysUser sysUser) {
        sysUserService.savesys(sysUser);
        return AjaxResult.success();

    }

    //修改
    @PostMapping("/update")
    public AjaxResult update(SysUser sysUser){
        sysUserService.update(sysUser);
        return AjaxResult.success();
    }

    //删除
    @PostMapping("/delete")
    public AjaxResult delete(String ids){
        String[] split = ids.split(",");
        Long[] arr = new Long[split.length];
        for (int i =0; i < split.length; i++){
            arr[i] = Long.parseLong(split[i]);
        }
        sysUserService.batchDelete(arr);
        return AjaxResult.success("删除成功");
    }

}

